package com.crx.springbootinit.manager;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.model.GeneratePresignedUrlRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.crx.springbootinit.config.CosClientConfig;
import java.io.File;
import java.net.URL;
import java.util.Date;
import javax.annotation.Resource;

import org.joda.time.DateTime;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * Cos 对象存储操作
 *
 
 */
@Component
public class CosManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private COSClient cosClient;

    /**
     * 上传对象
     *
     * @param key 唯一键
     * @param localFilePath 本地文件路径
     * @return
     */
    public PutObjectResult putObject(String key, String localFilePath) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucketPrivate(), key,
                new File(localFilePath));
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 上传对象
     *
     * @param key 唯一键
     * @param file 文件
     * @return
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucketPrivate(), key,
                file);
        return cosClient.putObject(putObjectRequest);
    }

    //获取临时签名URL
    public String getImageUrl(String path) {
        if(!StringUtils.hasText(path)) return "";
        //获取cosclient对象
        //GeneratePresignedUrlRequest
        GeneratePresignedUrlRequest request =
                new GeneratePresignedUrlRequest(cosClientConfig.getBucketPrivate(),
                        path, HttpMethodName.GET);
        //设置临时URL有效期为15分钟
        Date date = new DateTime().plusYears(1).toDate();
        request.setExpiration(date);
        //调用方法获取
        URL url = cosClient.generatePresignedUrl(request);
        return url.toString();
    }
}
